package com.hmall.search.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.client.ItemClient;
import com.hmall.common.dto.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParms;
import com.sun.org.apache.xpath.internal.objects.XObjectFactory;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transform.DeleteTransformRequest;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SearchService {
    @Autowired
    ItemClient itemClient;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public void saveItembyId(Long id) throws IOException {
         Item item = itemClient.select(id);
        final IndexRequest request = new IndexRequest("shizhan").id(id.toString());
        final ItemDoc itemDoc = new ItemDoc(item);
        request.source(JSONObject.toJSON(itemDoc), XContentType.JSON);
        restHighLevelClient.index(request,RequestOptions.DEFAULT);
    }

    public void deleteItembyId(Long id) throws IOException {
         DeleteRequest r = new DeleteRequest("shizhan",id.toString());

         restHighLevelClient.delete(r, RequestOptions.DEFAULT);

    }

    public PageDTO<ItemDoc> select(RequestParms params) throws IOException {
        final SearchRequest request = new SearchRequest("shizhan");
        int page =params.getPage();
        int size=params.getSize();
        request.source().from((page -1)*size).size(size);
        final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        final String key = params.getKey();
        if (key==null||"".equals(key)){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",key));
        }
        if (params.getBrand()!=null&& !params.getBrand().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        if (params.getCategory()!=null&& !params.getCategory().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("Category",params.getCategory()));
        }
        if (params.getMinPrice()!=null&&params.getMaxPrice()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        request.source().query(boolQueryBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
         List<ItemDoc> list = new ArrayList<>(hits1.length);
        for (SearchHit hit : hits1) {
           String json = hit.getSourceAsString();
             Map map = JSON.parseObject(json, Map.class);
            String id =map.get("id").toString();
            Boolean isAD = (Boolean) map.get("isAD");
            String sold = map.get("sold").toString();
            final String brand = map.get("brand").toString();
            final String category = map.get("category").toString();
            final String commentCount = map.get("commentCount").toString();
            final String image = map.get("image").toString();
            final String name = map.get("name").toString();
            final String price = map.get("price").toString();
            ItemDoc itemDoc = new ItemDoc();
            itemDoc.setId(id);
            itemDoc.setIsAD(isAD);
            itemDoc.setBrand(brand);
            itemDoc.setSold(sold);
            itemDoc.setCategory(category);
            itemDoc.setCommentCount(commentCount);
            itemDoc.setImage(image);
            itemDoc.setName(name);
            itemDoc.setPrice(price);

            list.add(itemDoc);
        }
        return new PageDTO<>(value,list);
    }


  /*  public PageDTO<ItemDoc> select(RequestParms params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("shizhan");
            // 2.准备DSL
            // 2.1.query条件
//            buildBasicQuery(request, params);
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            // 2.3.排序
            String sortBy = params.getSortBy();
            if ("sold".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.ASC);
            }
            // 2.4.高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            // 3.发请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            SearchHits searchHits = response.getHits();
            // 4.1.total
            long total = searchHits.getTotalHits().value;
            // 4.2.数据
            SearchHit[] hits = searchHits.getHits();
            // 4.3.遍历
            List<ItemDoc> list = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                // 4.4.获取source
                String json = hit.getSourceAsString();
                // 4.5.转Java
                ItemDoc itemDoc = MAPPER.readValue(json, ItemDoc.class);
                // 4.6.获取高亮
                Map<String, HighlightField> map = hit.getHighlightFields();
                if (map != null && map.size() > 0) {
                    HighlightField field = map.get("name");
                    String value = field.getFragments()[0].string();
                    itemDoc.setName(value);
                }
                list.add(itemDoc);
            }
            return new PageDTO<>(total, list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }*/
}
